<template>
  <div class="container">
    <el-row :gutter="10">
      <!-- 左树 -->
      <el-col :span="3">
        <el-card :style="`height: ${screenHeight - 85}px`">
          <el-tabs v-model="organization">
            <el-tab-pane label="组织架构" name="organization">
              <el-tree
                default-expand-all
                :expand-on-click-node="false"
                :data="deptDate"
                @node-click="handleNodeClick"
              ></el-tree>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>

      <!-- 右表 -->
      <el-col :span="21" :xs="24">
        <TableWrapper :title="'人员管理'" :footer="false" class="tableWrapper">
          <!-- 搜索头 -->
          <template #header>
            <el-form
              ref="form"
              :model="query"
              label-width="100px"
              :inline="true"
            >
              <el-form-item label="登录人员：">
                <el-input
                  style="width: 220px"
                  v-model="query.userName"
                  placeholder="请输入登录人员"
                ></el-input>
              </el-form-item>
              <el-form-item label="员工状态：">
                <el-select
                  style="width: 220px"
                  v-model="query.status"
                  placeholder="请选择员工状态"
                >
                  <el-option
                    v-for="item in dict.type.sys_normal_disable"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="员工岗位：">
                <Treeselect
                  style="width: 220px"
                  v-model="query.deptId"
                  placeholder="请选择部门"
                  :options="deptDate"
                  :show-count="true"
                ></Treeselect>
              </el-form-item>
              <el-form-item class="ml15">
                <el-button
                  icon="el-icon-search"
                  type="primary"
                  @click="searchChange"
                  >搜索</el-button
                >
                <el-button icon="el-icon-refresh-left" @click="searchReset"
                  >重置</el-button
                >
              </el-form-item>
            </el-form>
          </template>
          <!-- 表体 -->
          <template #main>
            <div style="margin-bottom: 18px">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                @click="$emit('TableListClick', 'add', 0)"
                v-hasPermission="['system:user:add']"
                >新增</el-button
              >
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                :disabled="selectionList.length == 0"
                v-hasPermission="['system:user:edit']"
                >批量删除</el-button
              >
              <el-button
                type="primary"
                plain
                icon="el-icon-refresh"
                @click="resetUserPassword"
                :disabled="selectionList.length == 0"
                v-hasPermission="['system:user:resetPwd']"
                >密码重置</el-button
              >
              <el-button
                type="warning"
                plain
                icon="el-icon-coordinate"
                :disabled="selectionList.length == 0"
                >账号解封</el-button
              >
              <el-button
                type="success"
                plain
                icon="el-icon-upload2"
                @click="dialogVisibleFileUpload = true"
                v-hasPermission="['system:user:import']"
                >导入</el-button
              >
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                v-hasPermission="['system:user:export']"
                @click="exportUserTable"
                >导出</el-button
              >
            </div>
            <el-table
              :data="data"
              @selection-change="selectionChange"
              style="width: 100%"
              :header-cell-style="headStyle"
            >
              <el-table-column align="center" type="selection" width="60">
              </el-table-column>
              <el-table-column
                align="center"
                label="序号"
                type="index"
                width="50"
              >
              </el-table-column>
              <el-table-column align="center" prop="userName" label="用户名">
              </el-table-column>
              <el-table-column align="center" prop="nickName" label="昵称">
              </el-table-column>
              <el-table-column align="center" prop="sex" label="性别">
                <template slot-scope="scope">
                  <dict-tag
                    :options="dict.type.sys_user_sex"
                    :value="scope.row.sex"
                  />
                </template>
              </el-table-column>
              <el-table-column align="center" prop="phonenumber" label="手机号">
              </el-table-column>
              <el-table-column align="center" prop="dept.deptName" label="部门">
              </el-table-column>
              <el-table-column align="center" prop="status" label="状态">
                <template slot-scope="scope">
                  <dict-tag
                    :options="dict.type.sys_normal_disable"
                    :value="scope.row.status"
                  />
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="200">
                <template slot-scope="scope">
                  <template
                    v-if="
                      !(
                        scope.row.userName === 'admin' &&
                        $store.getters.name !== 'admin'
                      )
                    "
                  >
                    <el-button
                      type="text"
                      icon="el-icon-paperclip"
                      size="small"
                      @click="handelOpenSetStatus(scope.row)"
                      v-hasPermission="['system:user:edit']"
                      >设置状态</el-button
                    >
                    <el-button
                      type="text"
                      icon="el-icon-edit"
                      size="small"
                      @click="$emit('TableListClick', 'edit', scope.row)"
                      v-hasPermission="['system:user:edit']"
                      >编辑</el-button
                    >
                    <el-button
                      type="text"
                      icon="el-icon-delete"
                      size="small"
                      v-hasPermission="['system:user:delete']"
                      >删除</el-button
                    >
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </template>

          <template #footer>
            <el-pagination
              @size-change="sizeChange"
              @current-change="currentChange"
              :current-page="page.currentPage"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="page.size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="page.total"
            >
            </el-pagination>
          </template>
        </TableWrapper>
      </el-col>
    </el-row>

    <el-dialog title="设置用户状态" :visible.sync="dialogVisible" width="15%">
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="用户编号：">
          <el-input v-model="form.userId" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户状态：">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="item in dict.type.sys_normal_disable"
              :key="item.value"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handelUpdateStatus">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="导入数据"
      :visible.sync="dialogVisibleFileUpload"
      width="20%"
    >
      <FileUpload
        :limit="1"
        :uploadFileUrl="'/system/user/import'"
      ></FileUpload>
    </el-dialog>
  </div>
</template>

<script>
import TableWrapper from "@/components/Table/TableWrapper.vue";
import FileUpload from "@/components/FileUpload/index.vue";
import {
  getList,
  resetPassword,
  updateStatus,
  exportList,
} from "@/api/system/user.js";
import { getDeptTree } from "@/api/system/dept.js";
import { getpostTree } from "@/api/system/post.js";
import download from "@/plugins/download.js";

export default {
  components: { TableWrapper, FileUpload },
  dicts: ["sys_user_sex", "sys_normal_disable"],
  data() {
    return {
      // 选中组织架构
      organization: "organization",
      // 详情数据
      form: {},
      // 搜索数据
      query: {},
      // 分页数据
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      defaultProps: {},
      // 树表数据
      deptDate: [],
      // 多选数据
      selectionList: [],
      // 表数据
      data: [],
      // 岗位树
      postTree: [],
      // 屏幕高度
      screenHeight: document.body.clientHeight,
      dialogVisible: false,
      dialogVisibleFileUpload: false,
    };
  },
  // 页面加载时触发
  created() {
    // 获取列表数据
    this.refreshChange();
    // 获取树表数据
    this.getTree();
    // 获取部门树
    getpostTree().then((res) => {
      this.postTree = res.data;
    });
  },
  mounted() {
    // 把window.onresize事件挂在到mounted函数上,这里就会一直监听大小变化
    window.onresize = () => {
      return (() => {
        this.screenHeight = document.documentElement.clientHeight; // 高
      })();
    };
  },
  methods: {
    // 搜索重置
    searchReset() {
      this.query = {};
      this.page.currentPage = 1;
      this.refreshChange();
    },
    // 搜索点击
    searchChange() {
      this.page.currentPage = 1;
      this.refreshChange();
    },
    // 多选发生改变
    selectionChange(list) {
      this.selectionClear();
      this.selectionList = list.map((v) => v.userId);
    },
    selectionClear() {
      this.selectionList = [];
    },
    // 当前分页发生改变
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.refreshChange();
    },
    // 分页大小发生改变
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.refreshChange();
    },
    // 刷新数据
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    // 重载数据
    onLoad(page, params = {}) {
      let values = {
        ...params,
        // 排序字段
        orderByColumn: "create_time",
        // 排序方式 desc 降序 asc 升序
        isAsc: "asc",
      };

      // 传递日期
      if (values.loginDate && values.loginDate.length == 2) {
        values.beginTime = params.loginDate[0];
        values.endTime = params.loginDate[1];
      }

      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(values, this.query)
      ).then((res) => {
        const data = res.data;
        this.page.total = data.total;
        this.data = data.records;
        this.selectionClear();
      });
    },
    // 获取树表数据
    getTree() {
      getDeptTree().then((res) => {
        this.deptDate = res.data;
      });
    },
    // 点击树事件
    handleNodeClick(row) {
      this.query.deptId = row.id;
      this.refreshChange();
    },
    // 自定义表头颜色
    headStyle({ row, rowIndex }) {
      // console.log(row, rowIndex)// row选中行数据，rowindex添加属性的元素下标
      if (rowIndex === 0) {
        return {
          backgroundColor: "#F8FAFF",
          fontWeight: 800,
          color: "#515a6e",
        };
      }
    },
    // 重置用户密码
    resetUserPassword() {
      resetPassword(...this.selectionList).then((res) => {
        if (res.code == 200) {
          this.$modal.msgSuccess(res.msg);
        } else {
          this.$modal.msgError(res.msg);
        }
      });
    },
    handelOpenSetStatus(row) {
      this.form = JSON.parse(JSON.stringify(row));
      this.dialogVisible = true;
    },
    exportUserTable() {
      exportList().then((res) => {
        download.downloadExcelExport(res, "用户信息.xls");
      });
    },
    handelUpdateStatus() {
      const { userId, status } = this.form;
      updateStatus(userId, status).then((res) => {
        if (res.code == 200) {
          this.$modal.msgSuccess(res.msg);
          this.refreshChange();
          this.dialogVisible = false;
        } else {
          this.$modal.msgError(res.msg);
        }
      });
    },
  },
};
</script>